import {getStorage, setStorageItem} from "@/utils/storage.js";
import {getUsersInfo, login, logout} from "@/api/index.js";
import { getRouters } from '@/api/menu.js'
import store from "@/store";
import {getPendingCount} from "@/api/vaction.js";
const state = {
    token: '' || getStorage('token'),
    userInfo: {}, // 用户信息
    approvalCount: 0, // 待审批数量
}

const mutations = {
    // 设置用户信息
    SET_USER_INFO(state, payload) {
        state.userInfo = payload
    },
    // 设置token
    SET_TOKEN(state, payload) {
        state.token = payload
        setStorageItem('token', payload)
    },
    // 设置待审批数量
    SET_APPROVAL_COUNT(state, payload) {
        state.approvalCount = payload
    }
}

const actions = {
    // 登录获取token
    login({commit}, userInfo) {
        const {userName, userPwd} = userInfo
        return new Promise((resolve, reject) => {
            login({userName: userName.trim(), userPwd: userPwd.trim()}).then(res => {
                commit('SET_TOKEN', res.data.token)
                resolve()
            }).catch(error => {
                reject(error)
            })
        })
    },
    // 获取路由
    getRouters({commit}, payload) {
        return new Promise((resolve, reject) => {
            getRouters(payload).then(res => {
                if (!res.data) {
                    reject('验证失败，请重新登录')
                }
                resolve(res.data)
            }).catch(error => {
                reject(error)
            })
        })
    },
    // 获取用户信息
    getUsersInfo({commit}) {
        return new Promise((resolve, reject) => {
            getUsersInfo().then(res => {
                if (!res.data) {
                    reject('验证失败，请重新登录')
                }
                commit('SET_USER_INFO', res.data)
                resolve(res.data)
            }).catch(error => {
                reject(error)
            })
        })
    },
    // 退出登录
    logout({commit}) {
        return new Promise((resolve, reject) => {
            logout().then(() => {
                // 清空用户信息
                commit('SET_USER_INFO', {})
                //  清空token
                commit('SET_TOKEN', '')
                // 清空路由
                store.commit('permission/SET_REMOVE_ROUTES')
                resolve()
            }).catch(error => {
                reject(error)
            })
        })
    },
    // 当前的待审批数量
    getApprovalCount({commit}) {
        return new Promise((resolve, reject) => {
            getPendingCount().then(res => {
                commit('SET_APPROVAL_COUNT', res.data)
                resolve(res.data)
            }).catch(error => {
                reject(error)
            })
        })
    }
}

export default {
    // 开启命名空间
    namespaced: true,
    state,
    mutations,
    actions
}
